package com.bank.controller;

import com.bank.entity.TradeInfo;
import com.bank.mapper.TradeInfoMapper;
import com.bank.service.TradeInfoService;
import com.bank.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 交易信息控制器
 */
@CrossOrigin
@RestController
@RequestMapping("/api/trade")
public class TradeInfoController {

    @Autowired
    private TradeInfoMapper tradeInfoMapper;

    @Autowired
    private TradeInfoService tradeInfoService;

    /**
     * 查询所有交易信息
     */
    @GetMapping("/list")
    public List<TradeInfo> list() {
        return tradeInfoMapper.findAll();
    }

    /**
     * 根据卡号查询交易信息
     */
    @GetMapping("/card/{cardID}")
    public List<TradeInfo> getByCardId(@PathVariable String cardID) {
        return tradeInfoMapper.findByCardId(cardID);
    }

    /**
     * 新增交易信息
     */
    @PostMapping
    public int add(@RequestBody TradeInfo tradeInfo) {
        return tradeInfoMapper.insert(tradeInfo);
    }

    /**
     * 删除交易信息
     */
    @DeleteMapping("/{cardID}/{tradeDate}")
    public int delete(@PathVariable String cardID, @PathVariable String tradeDate) {
        return tradeInfoMapper.delete(cardID, tradeDate);
    }

    @PostMapping("/deposit")
    public Result<Void> deposit(@RequestBody TradeInfo tradeInfo) {
        // 确保交易类型为"存入"
        tradeInfo.setTradeType("存入");
        boolean success = tradeInfoService.deposit(tradeInfo);
        if (success) {
            return Result.success();
        } else {
            return Result.error("存款失败");
        }
    }

    @PostMapping("/withdraw")
    public Result<Void> withdraw(@RequestBody TradeInfo tradeInfo) {
        // 确保交易类型为"支取"
        tradeInfo.setTradeType("支取");
        boolean success = tradeInfoService.withdraw(tradeInfo);
        if (success) {
            return Result.success();
        } else {
            return Result.error("余额不足或取款失败");
        }
    }

    @PostMapping("/transfer")
    public Result<Void> transfer(@RequestBody java.util.Map<String, Object> params) {
        String sourceCardID = (String) params.get("sourceCardID");
        String targetCardID = (String) params.get("targetCardID");
        java.math.BigDecimal amount = new java.math.BigDecimal(params.get("amount").toString());
        boolean success = tradeInfoService.transfer(sourceCardID, targetCardID, amount);
        if (success) {
            return Result.success();
        } else {
            return Result.error("转账失败，可能余额不足或卡号不存在");
        }
    }

    @GetMapping("/customer/{customerId}")
    public Result<List<TradeInfo>> getByCustomerId(@PathVariable Long customerId) {
        List<TradeInfo> list = tradeInfoMapper.findByCustomerId(customerId);
        return Result.success(list);
    }
}